from flask import Flask, render_template, request,session,redirect
import json
from . import common
import os
from frameworks.cores.Config import *
from frameworks.utils.JsonResult2 import *
from frameworks.cores.LoadClass import *

basepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)
from flask_session import Session

jsonResult = JsonResult2()

loader = LoadClass()

@common.route(env+"/console",methods=['GET', 'POST'])
def console():
    return render_template('/home/console.html')

@common.route(env+"/serverslist",methods=['GET', 'POST'])
def serverslist():
    con = loader.load("controller.CommonController",request.get_json())
    serverlist = con.run()
    return render_template('servers.html',
                           serverlist=serverlist
                           )

@common.route(env+"/cat",methods=['GET', 'POST'])
def cat():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'cat.html',
        dataurl="w="+dataurl,
        model=name
    )

@common.route(env+"/cat_read",methods=['GET', 'POST'])
def cat_read():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'cat_read.html',
        dataurl="w="+dataurl,
        model=name
    )

@common.route(env+"/cat_account",methods=['GET', 'POST'])
def cat_account():
    name = request.args.get("pagename","cat")
    where = request.args.get("w","")
    print(where)
    dataurl = ""
    params = []
    if where != "":
        whereOption = where.split("|")
        for row in whereOption:
            option = row.split("@")
            params.append(option[0]+"("+option[1]+")")
        print(params)
        dataurl = "||".join(params)

    return render_template(
        'cat_account.html',
        dataurl="w="+dataurl,
        model=name
    )

@common.route(env+"/update",methods=['POST'])
def update():
    model = request.args.get("model", "school")
    response = request.get_data(as_text=True)
    data = json.loads(response)
    if "userid" in data:
        data["userid"] = session["userid"]
    rs = loader.load("controller.CommonController", "CommonController", {
        "func": "update",
        "data": data,
        "model": model
    })
    return jsonResult.setOk([], "更新成功")

@common.route(env+"/delete",methods=['GET'])
def delete():
    id = request.args.get("id",0)
    model = request.args.get("model", "school")
    print(id)
    rs = loader.load("controller.CommonController", "CommonController", {
        "func": "delete",
        "data": {"id":id},
        "model": model
    })
    return jsonResult.setOk([], "删除成功")

@common.route(env+"/add",methods=['POST'])
def add():
    model = request.args.get("model", "school")
    response = request.get_data(as_text=True)
    data = json.loads(response)
    if "userid" in data:
        data["userid"] = session["userid"]
    rs = loader.load("controller.CommonController", "CommonController", {
        "func": "add",
        "data": data,
        "model": model
    })
    return jsonResult.setOk([], "添加成功")

@common.route(env+"/form",methods=['GET', 'POST'])
def form():
    model = request.args.get("model", "school")
    id = request.args.get("id", "0")
    fields = loader.load("controller.CommonController", "CommonController", {
        "func": "getEditMap",
        "fields": ["*"],
        "model": model
    })
    obj = loader.load("controller.CommonController","CommonController",{
        "func":"getRowData",
        "fields":["*"],
        "id": id,
        "model": model
    })
    wherestr = request.args.get("w", "")
    if wherestr.find(")") > 0 and wherestr.find("(") > 0:
        whereoption = wherestr.replace(")", "").split("(")
        data = {whereoption[0]: whereoption[1]}
    else:
        data = []
    return render_template(
        'form.html',
        obj=obj[0],
        fields=fields,
        model=model,
        data=data
    )

@common.route(env+"/formadd",methods=['GET', 'POST'])
def formadd():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w", "")
    fields = loader.load("controller.CommonController","CommonController",{
        "func":"getAddMap",
        "fields":["*"],
        "model": model
    })
    if wherestr.find(")") > 0 and wherestr.find("(") > 0:
        whereoption = wherestr.replace(")","").split("(")
        data = {whereoption[0]:whereoption[1]}
    else:
        data = []
    return render_template(
        'formadd.html',
        fields=fields,
        model=model,
        data=data
    )

@common.route(env+"/cols",methods=['GET','POST'])
def cols():
    model = request.args.get("model", "school")
    width = request.args.get("width", "200")
    if model in ["users"]:
        fields = ["id","username"]
    else:
        fields = "*"
    rs = loader.load("controller.CommonController", "CommonController", {
        "func":"getColumns",
        "fields":fields,
        "model":model,
        "width":width
    })
    return jsonResult.setOk(rs,"获取成功")

@common.route(env+"/listdata",methods=['GET'])
def listdata():
    model = request.args.get("model", "school")
    wherestr = request.args.get("w", "")
    num = request.args.get("limit",10)
    page = request.args.get("page",1)
    if wherestr != "":
        wherestr = wherestr.replace("(", "='").replace(")", "'").replace("||", " and ")
    else:
        wherestr = "1"
    fields = []
    if model in ["users"]:
        wherestr += " and id="+str(session["userid"])
        fields.append("id,username")
    else:
        fields.append("*")

    data = loader.load("controller.CommonController", "CommonController", {
        "func": "getData",
        "fields": fields,
        "page": page,
        "num": num,
        "orderfield": "id",
        "asc": "asc",
        "model": model,
        "where": wherestr
    })
    return json.dumps(data)


